package com.ncmmall.mall.controller.business.distribution;

import com.ncmmall.application.business.distribution.DistributorApplication;
import com.feijin.commons.lang.Requires;
import com.ncmmall.domain.business.distribution.Distributor;
import com.ncmmall.domain.business.distribution.DistributorLevel;
import com.ncmmall.domain.business.distribution.QDistributor;
import com.ncmmall.domain.business.distribution.QDistributorLevel;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分销商管理
 *
 * @author likaikai
 * @date 2020-8-22 15:51:23
 */
@Controller
@RequestMapping("/distributor")
@Slf4j
public class DistributorController {

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private DistributorApplication distributorApplication;

    /**
     * 分销商列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model,
                       @RequestParam(defaultValue = "1") int pageNo,
                       @RequestParam(defaultValue = "10") int pageSize,
                       Distributor params) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageNo).setPageSize(pageSize);
        String hql = "select d from Distributor d where 1 = 1";
        Map<String, Object> map = new HashMap<>();
        hql = buildHQL(hql, params, map);

        QueryPage<Distributor> page = queryChannelService.findPage(hql, pageRequest.setParams(map), Distributor.class);
        model.addAttribute("page", page);
        model.addAttribute("params", params);
        model.addAttribute("levels", queryChannelService.findAll("select l from DistributorLevel l", DistributorLevel.class));

        return "mall/distribution/distributor/list";
    }

    private String buildHQL(String hql, Distributor params, Map<String, Object> map) {

        WebUser user = params.getUser();
        if (user != null) {
            if (StringUtils.isNotBlank(user.getMobile())) {
                hql += " and d.user.mobile like :mobile";
                map.put("mobile", "%" + user.getMobile() + "%");
            }

            if (StringUtils.isNotBlank(user.getRealName())) {
                hql += " and d.user.realName like :realName";
                map.put("realName", "%" + user.getRealName() + "%");
            }
        }

        if (params.getAccountStatus() != null) {
            hql += " and d.accountStatus = :accountStatus";
            map.put("accountStatus", params.getAccountStatus());
        }

        if (params.getLevel() != null && params.getLevel().getLevel() != null && params.getLevel().getLevel() > 0) {
            hql += " and d.level.level = :level";
            map.put("level", params.getLevel().getLevel());
        }

        if (params.getSource() != null) {
            hql += " and d.source = :source";
            map.put("source", params.getSource());
        }

        hql += " order by d.createTime desc";

        return hql;
    }


    /**
     * 新增分销商
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {

        model.addAttribute("levels", queryChannelService.findAll("select l from DistributorLevel l", DistributorLevel.class));
        model.addAttribute("distributor", new Distributor());

        return "mall/distribution/distributor/form";
    }

    /**
     * 新增分销商
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> create(Distributor params) {
        try {
            distributorApplication.create(params);
            return ImmutableMap.of("status", true, "message", "添加成功");
        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[新增分销商异常]", e);
            return ImmutableMap.of("status", false, "message", "添加异常");
        }
    }


    /**
     * 会员选择(只有会员才能成为分销商)
     */
    @RequestMapping(value = "/selectUser", method = RequestMethod.GET)
    public String selectUser(WebUser user, @RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "10") int pageSize, Model model) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageNo).setPageSize(pageSize);
        Map<String, Object> params = new HashMap<>();
        String hql = builderSQL("select u from WebUser u where u.role.name = 'MEMBER' and (u.distributor is null or u.distributor = false) ", params, user);
        QueryPage<WebUser> page = queryChannelService.findPage(hql, pageRequest.setParams(params), WebUser.class);
        model.addAttribute("page", page).addAttribute("params", user);
        return "mall/distribution/distributor/selectUser";
    }

    private String builderSQL(String hql, Map<String, Object> params, WebUser member) {

        if (!Strings.isNullOrEmpty(member.getRealName())) {
            hql += " and u.realName like :realname ";
            params.put("realname", "%" + member.getRealName() + "%");
        }

        if (!Strings.isNullOrEmpty(member.getMobile())) {
            hql += " and u.mobile like :mobile ";
            params.put("mobile", "%" + member.getMobile() + "%");
        }

        if (member.getFather() != null && StringUtils.isNotBlank(member.getFather().getRealName())) {
            hql += " and u.father.realName like :fatherRealName ";
            params.put("fatherRealName", "%" + member.getFather().getRealName() + "%");
        }

        if (member.getFather() != null && StringUtils.isNotBlank(member.getFather().getMobile())) {
            hql += " and u.father.mobile like :fatherMobile ";
            params.put("fatherMobile", "%" + member.getFather().getMobile() + "%");
        }

        return hql + " order by u.createTime desc ";
    }

    /**
     * 禁用
     */
    @RequestMapping(value = "/disableAccount", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> disableAccount(long id) {
        try {
            Distributor distributor = queryChannelService.findOne(QDistributor.distributor.id.eq(id), Distributor.class);
            distributorApplication.disableAccount(distributor);
            return ImmutableMap.of("status", true, "message", "禁用成功");
        } catch (Exception e) {
            log.error("禁用分销商帐号异常", e);
            return ImmutableMap.of("status", false, "message", "禁用异常");
        }
    }

    /**
     * 批量禁用
     */
    @RequestMapping(value = "/disableAccounts", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> disableAccounts(String ids) {
        try {
            Requires.hasLength(ids, "请选择操作对象");
            List<Long> longIds = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(ids).stream().map(Long::valueOf).collect(Collectors.toList());
            List<Distributor> distributors = queryChannelService.findAll(QDistributor.distributor.id.in(longIds), Distributor.class);
            distributorApplication.disableAccounts(distributors);
            return ImmutableMap.of("status", true, "message", "禁用成功");
        } catch (Exception e) {
            log.error("禁用分销商帐号异常", e);
            return ImmutableMap.of("status", false, "message", "禁用异常");
        }
    }

    /**
     * 启用
     */
    @RequestMapping(value = "/enableAccount", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> enableAccount(long id) {
        try {
            Distributor distributor = queryChannelService.findOne(QDistributor.distributor.id.eq(id), Distributor.class);
            distributorApplication.enableAccount(distributor);
            return ImmutableMap.of("status", true, "message", "启用成功");
        } catch (Exception e) {
            log.error("启用分销商帐号异常", e);
            return ImmutableMap.of("status", false, "message", "启用异常");
        }
    }

    /**
     * 批量启用
     */
    @RequestMapping(value = "/enableAccounts", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> enableAccounts(String ids) {
        try {
            Requires.hasLength(ids, "请选择操作对象");
            List<Long> longIds = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(ids).stream().map(Long::valueOf).collect(Collectors.toList());
            List<Distributor> distributors = queryChannelService.findAll(QDistributor.distributor.id.in(longIds), Distributor.class);
            distributorApplication.enableAccounts(distributors);
            return ImmutableMap.of("status", true, "message", "启用成功");
        } catch (Exception e) {
            log.error("启用分销商帐号异常", e);
            return ImmutableMap.of("status", false, "message", "启用异常");
        }
    }

    /**
     * 修改分销商等级
     */
    @RequestMapping(value = "/{id}/modifyLevel", method = RequestMethod.GET)
    private String modifyLevel(Model model, @PathVariable("id") long id) {

        Distributor distributor = queryChannelService.findOne(Distributor.class, id);
        List<DistributorLevel> distributorLevels = queryChannelService.findAll("select d from DistributorLevel d", DistributorLevel.class);
        model.addAttribute("distributor", distributor)
                .addAttribute("distributorLevels", distributorLevels)
                .addAttribute("_method", "PUT");

        return "mall/distribution/distributor/modifyLevel";
    }


    /**
     * 修改分销商等级
     */
    @RequestMapping(value = "/{id}/modifyLevel", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> modifyLevel(@PathVariable("id") long id, long levelId) {
        try {
            Distributor distributor = queryChannelService.findOne(QDistributor.distributor.id.eq(id), Distributor.class);
            DistributorLevel level = queryChannelService.findOne(QDistributorLevel.distributorLevel.id.eq(levelId), DistributorLevel.class);
            distributorApplication.modifyLevel(Collections.singletonList(distributor), level);
            return ImmutableMap.of("status", true, "message", "修改成功");
        } catch (Exception e) {
            log.error("修改分销商等级异常", e);
            return ImmutableMap.of("status", false, "message", "修改异常");
        }
    }

    /**
     * 批量修改分销商等级
     */
    @RequestMapping(value = "/{ids}/modifyLevels", method = RequestMethod.GET)
    private String modifyLevels(Model model) {

        List<DistributorLevel> distributorLevels = queryChannelService.findAll("select d from DistributorLevel d", DistributorLevel.class);
        model.addAttribute("distributor", new Distributor())
                .addAttribute("distributorLevels", distributorLevels)
                .addAttribute("_method", "PUT");

        return "mall/distribution/distributor/modifyLevel";
    }

    /**
     * 批量修改分销商等级
     */
    @RequestMapping(value = "/{ids}/modifyLevels", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> modifyLevels(@PathVariable("ids") String ids, long levelId) {
        try {
            Requires.hasLength(ids, "请选择操作对象");
            List<Long> longIds = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(ids).stream().map(Long::valueOf).collect(Collectors.toList());
            List<Distributor> distributors = queryChannelService.findAll(QDistributor.distributor.id.in(longIds), Distributor.class);
            DistributorLevel level = queryChannelService.findOne(QDistributorLevel.distributorLevel.id.eq(levelId), DistributorLevel.class);
            distributorApplication.modifyLevel(distributors, level);
            return ImmutableMap.of("status", true, "message", "修改成功");
        } catch (Exception e) {
            log.error("修改分销商等级异常", e);
            return ImmutableMap.of("status", false, "message", "修改异常");
        }
    }

    /**
     * 修改推荐人
     */
    @RequestMapping(value = "/modifyFather", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> modifyFather(long distributorId, long fatherId) {
        try {
            Distributor distributor = queryChannelService.findOne(QDistributor.distributor.id.eq(distributorId), Distributor.class);
            WebUser father = queryChannelService.findOne(QWebUser.webUser.id.eq(fatherId), WebUser.class);
            distributorApplication.modifyFather(Collections.singletonList(distributor), father);
            return ImmutableMap.of("status", true, "message", "修改成功");
        } catch (Exception e) {
            log.error("修改分销商推荐人异常");
            return ImmutableMap.of("status", false, "message", "修改异常");
        }
    }

    /**
     * 批量修改推荐人
     */
    @RequestMapping(value = "/modifyFathers", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> modifyFathers(String distributorIds, long fatherId) {
        try {
            Requires.hasLength(distributorIds, "请选择操作对象");
            List<Long> longIds = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(distributorIds).stream().map(Long::valueOf).collect(Collectors.toList());
            List<Distributor> distributors = queryChannelService.findAll(QDistributor.distributor.id.in(longIds), Distributor.class);
            WebUser father = queryChannelService.findOne(QWebUser.webUser.id.eq(fatherId), WebUser.class);
            distributorApplication.modifyFather(distributors, father);
            return ImmutableMap.of("status", true, "message", "修改成功");
        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("批量修改分销商推荐人异常");
            return ImmutableMap.of("status", false, "message", "修改异常");
        }
    }


    /**
     * 关闭微店
     */
    @RequestMapping(value = "/disableShop", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> disableShop(long id) {
        try {
            Distributor distributor = queryChannelService.findOne(QDistributor.distributor.id.eq(id), Distributor.class);
            distributorApplication.disableShop(distributor);
            return ImmutableMap.of("status", true, "message", "关闭微店成功");
        } catch (Exception e) {
            log.error("关闭微店异常", e);
            return ImmutableMap.of("status", false, "message", "关闭微店异常");
        }
    }

    /**
     * 批量关闭微店
     */
    @RequestMapping(value = "/disableShops", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> disableShops(String ids) {
        try {
            Requires.hasLength(ids, "请选择操作对象");
            List<Long> longIds = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(ids).stream().map(Long::valueOf).collect(Collectors.toList());
            List<Distributor> distributors = queryChannelService.findAll(QDistributor.distributor.id.in(longIds), Distributor.class);
            distributorApplication.disableShops(distributors);
            return ImmutableMap.of("status", true, "message", "关闭微店成功");
        } catch (Exception e) {
            log.error("批量关闭微店异常", e);
            return ImmutableMap.of("status", false, "message", "关闭微店异常");
        }
    }

    /**
     * 开启微店
     */
    @RequestMapping(value = "/enableShop", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> enableShop(long id) {
        try {
            Distributor distributor = queryChannelService.findOne(QDistributor.distributor.id.eq(id), Distributor.class);
            distributorApplication.enableShop(distributor);
            return ImmutableMap.of("status", true, "message", "开启微店成功");
        } catch (Exception e) {
            log.error("开启微店异常", e);
            return ImmutableMap.of("status", false, "message", "开启微店异常");
        }
    }

    /**
     * 批量开启微店
     */
    @RequestMapping(value = "/enableShops", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> enableShops(String ids) {
        try {
            Requires.hasLength(ids, "请选择操作对象");
            List<Long> longIds = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(ids).stream().map(Long::valueOf).collect(Collectors.toList());
            List<Distributor> distributors = queryChannelService.findAll(QDistributor.distributor.id.in(longIds), Distributor.class);
            distributorApplication.enableShops(distributors);
            return ImmutableMap.of("status", true, "message", "开启微店成功");
        } catch (Exception e) {
            log.error("批量开启微店异常", e);
            return ImmutableMap.of("status", false, "message", "开启微店异常");
        }
    }


    /**
     * 选择隶属邀请人
     */
    @RequestMapping(value = "/{id}/invitePeopleList", method = RequestMethod.GET)
    private String invitePeopleList(Model model, PageParams pageParams, WebUser params, @PathVariable("id") long id) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageSize(pageParams.getPageSize()).setPageNo(pageParams.getPageNo());
        Map<String, Object> map = Maps.newHashMap();
        String sql = "select w from WebUser w where w.distributor is not null and w.id != :id";
        map.put("id", queryChannelService.findOne(QDistributor.distributor.id.eq(id), Distributor.class).getUser().getId());
        if (StringUtils.isNotBlank(params.getUsername())) {
            sql += " and w.username like :username";
            map.put("username", "%" + params.getUsername() + "%");
        }

        QueryPage<WebUser> page = queryChannelService.findPage(sql, pageRequest.setParams(map), WebUser.class);
        for (WebUser webUser : page.getResult()) {
            webUser.setSubordinateNum(queryChannelService.selectCount("select count(*) from security_web_user where father_id = :fid", ImmutableMap.of("fid", webUser.getId())));
        }

        model.addAttribute("params", params)
                .addAttribute("user", new WebUser())
                .addAttribute("page", page)
                .addAttribute("userId", id)
                .addAttribute("_method", "PUT");

        return "mall/distribution/distributor/invitePeopleList";
    }

    /**
     * 选择隶属邀请人
     */
    @RequestMapping(value = "/{id}/invitePeopleList", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> invitePeopleList(@PathVariable("id") String userId, long id) {
        try {
            if (StringUtils.isBlank(userId) || id <= 0) {
                return ImmutableMap.of("status", false, "message", "参数不正确");
            }

            distributorApplication.bindInvitePeople(userId, id);
            return ImmutableMap.of("status", true, "message", "修改成功");
        } catch (Exception e) {
            log.error("修改分销商的邀请人异常", e);
            return ImmutableMap.of("status", false, "message", "修改异常");
        }
    }

    /**
     * 批量修改邀请人
     */
    @RequestMapping(value = "/{ids}/invitePeopleLists", method = RequestMethod.GET)
    private String invitePeopleLists(Model model, PageParams pageParams, WebUser params) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageSize(pageParams.getPageSize()).setPageNo(pageParams.getPageNo());
        Map<String, Object> map = Maps.newHashMap();
        String sql = "select w from WebUser w where w.distributor.id is not null";

        QueryPage<WebUser> page = queryChannelService.findPage(sql, pageRequest.setParams(map), WebUser.class);
        for (WebUser webUser : page.getResult()) {
            webUser.setSubordinateNum(queryChannelService.selectCount("select count(*) from security_web_user where father_id = :fid", ImmutableMap.of("fid", webUser.getId())));
        }

        model.addAttribute("params", params)
                .addAttribute("page", page)
                .addAttribute("user", new WebUser())
                .addAttribute("_method", "PUT");

        return "mall/distribution/distributor/invitePeopleList";
    }

    /**
     * 批量修改邀请人
     */
    @RequestMapping(value = "/{ids}/invitePeopleLists", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> invitePeopleLists(@PathVariable("ids") String ids, long userId) {
        try {
            Requires.hasLength(ids, "请选择操作对象");
            List<String> longIds = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(ids).stream().map(String::valueOf).collect(Collectors.toList());
            distributorApplication.bindInvitePeoples(longIds, userId);
            return ImmutableMap.of("status", true, "message", "修改成功");
        } catch (Exception e) {
            log.error("批量修改邀请人异常", e);
            return ImmutableMap.of("status", false, "message", "修改异常");
        }
    }

    /**
     * 查看下级会员
     */
    @RequestMapping(value = "/{did}/subordinateList", method = RequestMethod.GET)
    private String subordinateList(Model model, PageParams pageParams, WebUser params, @PathVariable("did") long id, @RequestParam(defaultValue = "1") int type) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageSize(pageParams.getPageSize()).setPageNo(pageParams.getPageNo());
        Map<String, Object> map = new HashMap<>();
        String sql = "select w from WebUser w where w.distributor = null and w.role.name not in ('ADMIN', 'SYSTEM', 'MERCHANT')";
        if (type == 1) {
            sql += " and w.father.id = :id";
        } else if (type == 2) {
            sql += " and w.id != :id and w.father.id = null";
        }
        map.put("id", queryChannelService.findOne(QDistributor.distributor.id.eq(id), Distributor.class).getUser().getId());

        if (StringUtils.isNotBlank(params.getUsername())) {
            sql += " and w.username like :username";
            map.put("username", "%" + params.getUsername() + "%");
        }

        if (StringUtils.isNotBlank(params.getMobile())) {
            sql += " and w.mobile like :mobile";
            map.put("mobile", "%" + params.getMobile() + "%");
        }

        QueryPage<WebUser> page = queryChannelService.findPage(sql, pageRequest.setParams(map), WebUser.class);

        model.addAttribute("params", params)
                .addAttribute("page", page)
                .addAttribute("userId", id)
                .addAttribute("type", type)
                .addAttribute("_method", "PUT");

        return "mall/distribution/distributor/subordinateList";
    }

    /**
     * 删除下级
     */
    @RequestMapping(value = "/removeSubordinate", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> removeSubordinate(long id) {
        try {
            if (id <= 0) {
                return ImmutableMap.of("status", false, "mssage", "删除下级异常");
            }
            distributorApplication.removeSubordinate(id);
            return ImmutableMap.of("status", true, "message", "删除下级成功");
        } catch (Exception e) {
            log.error("删除下级异常", e);
            return ImmutableMap.of("status", false, "message", "删除下级异常");
        }
    }

    /**
     * 添加下级
     */
    @RequestMapping(value = "/addSubordinate", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> addSubordinate(long id, long userId) {
        try {
            if (id <= 0 || userId <= 0) {
                return ImmutableMap.of("status", false, "mssage", "添加下级异常");
            }

            distributorApplication.addSubordinate(id, userId);
            return ImmutableMap.of("status", true, "message", "添加下级成功");
        } catch (Exception e) {
            log.error("删除下级异常", e);
            return ImmutableMap.of("status", false, "message", "添加下级异常");
        }
    }


    /**
     * 查看下级分销商
     */
    @RequestMapping(value = "/{did}/distributorList", method = RequestMethod.GET)
    private String distributorList(Model model, QueryPageRequest pageRequest, WebUser params,
                                   @PathVariable("did") long id,
                                   @RequestParam(defaultValue = "1") int type) {

        Map<String, Object> map = new HashMap<>();
        String sql = "select w from WebUser w where w.distributor != null and w.role.name not in ('ADMIN', 'SYSTEM', 'MERCHANT')";

        if (type == 1) {
            sql += " and w.father.id = :id";
        } else if (type == 2) {
            sql += " and w.id != :id and w.father = null";
        }
        map.put("id", queryChannelService.findOne(QDistributor.distributor.id.eq(id), Distributor.class).getUser().getId());

        if (StringUtils.isNotBlank(params.getUsername())) {
            sql += " and w.username like :username";
            map.put("username", "%" + params.getUsername() + "%");
        }

        if (StringUtils.isNotBlank(params.getMobile())) {
            sql += " and w.mobile = :mobile";
            map.put("mobile", params.getMobile());
        }

        QueryPage<WebUser> page = queryChannelService.findPage(sql, pageRequest.setParams(map), WebUser.class);
        for (WebUser webUser : page.getResult()) {
            webUser.setData(webUser.getDistributor().getLevel().getName());
        }

        model.addAttribute("params", params)
                .addAttribute("page", page)
                .addAttribute("userId", id)
                .addAttribute("type", type)
                .addAttribute("_method", "PUT");

        return "mall/distribution/distributor/distributorList";
    }

}
